//
//  XPTextView.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/19.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

@IBDesignable
class XPTextView: UITextView {

    private lazy var placeHolderLabel: UILabel = {
        let placeHolderLabel = UILabel()
        placeHolderLabel.textColor = UIColor.darkGrayColor()
        placeHolderLabel.numberOfLines = 0
        return placeHolderLabel
    }()
    
    
    @IBInspectable var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeHolderLabel.font = font
        }
    }
    
    override var text: String? {
        didSet {
            placeHolderLabel.hidden = self.hasText()
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
       super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setupUI() {
        addSubview(placeHolderLabel)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XPTextView.textViewTextChange), name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    func textViewTextChange() {
        placeHolderLabel.hidden = self.hasText()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeHolderLabel.frame = CGRectMake(5, 5, screenWidth - 10, 0)
        placeHolderLabel.sizeToFit()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
